<template>
	<el-card>
		<Condition v-model:condition="condition" :btns="['search', 'reset']" @search="conditionSearch" @reset="conditionReset">
			<el-button v-auth="'sys:role:delete'" :icon="Delete" type="primary" @click="delSelect">批量删除</el-button>
			<el-button v-auth="'sys:role:save'" :icon="Plus" type="primary" @click="add">新建</el-button>
		</Condition>
		<!-- <el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item>
				<el-input v-model="state.queryForm.name" placeholder="名称" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="getDataList()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:role:save'" type="primary" @click="addOrUpdateHandle()">新增</el-button>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:role:delete'" type="danger" @click="deleteBatchHandle()">删除</el-button>
			</el-form-item>
		</el-form> -->
		<el-table v-loading="loading" :data="List" border style="width: 100%" @selection-change="selection">
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column prop="id" label="序号" header-align="center" align="center" width="80">
				<template #default="scope">
					{{ (pagination.page - 1) * pagination.limit + scope.$index + 1 }}
				</template>
			</el-table-column>
			<el-table-column prop="name" label="角色名称" header-align="center" align="center"></el-table-column>
			<el-table-column prop="platformName" label="所属平台" header-align="center" align="center">
				<template #default="scope">
					{{ scope.row.platformName }}
					<span style="color: red" v-if="!scope.row.platforms.length">(已解绑)</span>
				</template>
			</el-table-column>
			<el-table-column prop="memberNumber" label="成员个数" header-align="center" align="center" width="100"></el-table-column>
			<el-table-column prop="creator" label="创建人" header-align="center" align="center" width="180"></el-table-column>
			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center" width="180">
				<template #default="scope">
					{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="260">
				<template #default="scope">
					<el-button v-auth="'sys:role:detail'" type="primary" link @click="details(scope.row)">详情</el-button>
					<el-button v-auth="'sys:role:update'" type="primary" link @click="update(scope.row)">编辑</el-button>
					<el-button v-auth="'sys:role:connect'" type="primary" link @click="handleCommand(scope.row)">关联用户</el-button>
					<el-button v-auth="'sys:role:delete'" type="primary" link @click="del(scope.row)">删除</el-button>

					<!-- <el-dropdown v-auth="'sys:role:update'" @command="(command: string) => handleCommand(command, scope.row)">
						<el-button type="primary" class="el-dropdown-link" link>更多</el-button>
						<template #dropdown>
							<el-dropdown-menu>
								<el-dropdown-item command="dataScope">数据权限</el-dropdown-item>
								<el-dropdown-item command="user">分配用户</el-dropdown-item>
							</el-dropdown-menu>
						</template>
					</el-dropdown> -->
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="pagination.page"
			:page-sizes="pagination.pageSizes"
			:page-size="pagination.limit"
			:total="pagination.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChange"
			@current-change="currentChange"
		>
		</el-pagination>
		<el-dialog v-model="dialog.visible" :title="dialog.title" :close-on-click-modal="false" draggable>
			<Form ref="modalForm" v-model:formState="formState" :formData="formData"></Form>
			<template v-if="dialog.state !== 'details'" #footer>
				<el-button @click="dialog.visible = false">取消</el-button>
				<el-button type="primary" @click="dialogSave" :loading="dialog.loading">确定</el-button>
			</template>
		</el-dialog>
		<!-- 弹窗, 新增 / 修改 -->
		<!-- <add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update> -->
		<!-- 数据权限 -->
		<data-scope ref="dataScopeRef"></data-scope>
		<!-- 分配用户 -->
		<el-drawer v-if="userVisible" v-model="userVisible" :title="userTitle" :size="1000" :close-on-press-escape="false">
			<user :role-id="roleId"></user>
		</el-drawer>
	</el-card>
</template>

<script setup lang="ts">
import { Delete, Plus } from '@element-plus/icons-vue'
import { useCrud } from '@/hooks'
import { onMounted, reactive, ref } from 'vue'
import AddOrUpdate from './add-or-update.vue'
import DataScope from './data-scope.vue'
import User from './user.vue'
import { IHooksOptions } from '@/hooks/interface'
import { valueReset, valuable, typeOf, transMap } from '@/utils/tool'
import Condition from '@/components/Condition/index.vue'
import Form from '@/components/Form/index.vue'
import service from '@/utils/request'
import store from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils/tool'

const select = ref([])

const selection = e => {
	select.value = e
}

const loading = ref(false)
const List = ref([])
const pagination = ref({
	page: 1,
	limit: 20,
	total: 0,
	pageSizes: [10, 20, 50, 100, 200]
})

const sizeChange = val => {
	pagination.value = {
		...pagination.value,
		page: 1,
		limit: val
	}
	getList()
}
const currentChange = val => {
	pagination.value = {
		...pagination.value,
		page: val
	}
	getList()
}

const condition = ref<P.conditionItem[]>([
	{ dataIndex: 'day', type: 'dayRange', value: ['', ''] },
	{ dataIndex: 'name', type: 'input', value: '', placeholder: '请输入角色名称' },
	{ dataIndex: 'platformId', type: 'select', value: '', data: [], placeholder: '请选择平台' }
])

const conditionSearch = () => {
	pagination.value.page = 1
	getList()
}

const conditionReset = () => {
	condition.value.map(v => {
		v.value = valueReset(v.value) || ''
	})
	pagination.value.page = 1
	getList()
}

const dialog = ref({
	title: '新增机构',
	type: 'add',
	visible: false,
	loading: false
})

const delSelect = () => {
	if (!select.value.length) {
		ElMessage({
			message: '请选择删除记录',
			type: 'warning'
		})
		return
	}
	ElMessageBox.confirm(`确定要批量删除吗?此操作执行后不可恢复，请谨慎操作!`, '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			const ids = select.value.map(v => {
				return v.id
			})
			service.post('/sys/role/delete', ids).then(res => {
				if (res.code === 0) {
					ElMessage({
						message: '删除成功!',
						type: 'success'
					})
					getList()
				} else {
					ElMessage({
						message: res.message,
						type: 'error'
					})
				}
			})
		})
		.catch(() => {
			console.log('取消')
		})
}

onMounted(() => {
	getList()
	getPlatformList()

	const user = store.userStore.user
	const item = formData.value.find(v => {
		return v.dataIndex === 'orgId'
	})

	item.data = [
		{
			label: user.orgName,
			value: user.orgId
		}
	]
	formState.value.orgId = user.orgId
})

const getPlatformList = () => {
	const user = store.userStore.user
	const params = {
		orgId: user.orgId
	}
	service
		.get('/sys/org/platformOrgList', {
			params: params
		})
		.then(res => {
			res.data.map(v => {
				v['label'] = v.platformName
				v['value'] = v.id
			})
			const item = formData.value.find(v => {
				return v.dataIndex === 'platformId'
			})
			// let arr = []
			// res.data.map(v => {
			// 	if (v.children.length) {
			// 		v.children.map(u => {
			// 			u['value'] = u.id
			// 		})
			// 		v['value'] = v.id
			// 		arr.push(v)
			// 	}
			// })
			// item.data = arr
			item.data = res.data
			const item2 = condition.value.find(v => {
				return v.dataIndex === 'platformId'
			})
			item2.data = res.data
		})
}

const platformChange = (e, t) => {
	const item = formData.value.find(v => {
		return v.dataIndex === 'menuIdList'
	})
	if (e || e === 0) {
		getMenu(e)
		if (t !== 'first') {
			// 不是编辑或详情第一次进来就清空树形选中
			item.data = []
			formState.value.menuIdList = []
		}
	} else {
		item.data = []
		formState.value.menuIdList = []
	}
}

const getMenu = e => {
	const params = {
		platformId: e
	}
	service.post('/sys/platform/platformMenuList', params).then(res => {
		const data = transMap(res.data)

		const item = formData.value.find(v => {
			return v.dataIndex === 'menuIdList'
		})
		item.data = data
	})
}

const modalForm = ref()

const formState = ref({
	id: '',
	orgId: '',
	name: '',
	menuIdList: [],
	platformId: ''
})

const formData = ref([
	{
		title: '所属机构',
		dataIndex: 'orgId',
		type: 'select',
		data: [],
		disabled: true
	},
	{
		title: '角色名称',
		dataIndex: 'name',
		type: 'input',
		disabled: false,
		rules: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
	},
	{
		title: '所属平台',
		dataIndex: 'platformId',
		type: 'select',
		data: [],
		disabled: false,
		change: platformChange,
		rules: [{ required: true, message: '请选择所属平台', trigger: 'change' }]
	},
	{
		title: '角色权限',
		dataIndex: 'menuIdList',
		type: 'tree',
		split: true,
		key: 'id',
		data: [],
		disabled: false,
		label: 'label'
	}
])

const formState_reset = item => {
	modalForm.value && modalForm.value.reset()
	const obj = {
		id: '',
		name: '',
		menuIdList: [],
		platformId: ''
	}
	if (item) {
		for (let key in obj) {
			obj[key] = item[key]
		}
	}
	formState.value = { ...formState.value, ...obj }
}

const getList = () => {
	select.value = []
	loading.value = true
	let obj = condition.value.reduce((p, c) => {
		if (valuable(c.value)) {
			if (c.dataIndex === 'day') {
				p['startTime'] = c.value[0]
				p['endTime'] = c.value[1]
			} else {
				p[c.dataIndex] = c.value
			}
		}
		return p
	}, {})

	const { page, limit } = pagination.value
	service
		.get('/sys/role/page', {
			params: { ...obj, page, limit, orgId: store.userStore.user.orgId }
		})
		.then(res => {
			loading.value = false
			if (res.code === 0) {
				List.value = res.data.list
				pagination.value.total = res.data.total
			}
		})
		.catch(() => {
			loading.value = false
		})
}

const add = () => {
	dialog.value.state = 'add'
	dialog.value.title = '新建角色'
	formState_reset()

	formData.value.map(v => {
		if (v.dataIndex === 'orgId') {
			v.disabled = true
		} else {
			v.disabled = false
		}
	})

	platformChange()
	dialog.value.visible = true
}

const updateBefore = item => {
	return new Promise((resolve, reject) => {
		if (!item.platforms.length) {
			ElMessage({
				message: `系统检测到当前角色下的【${item.platformName}】平台已被取消关联，角色不可用，请联系管理员！`,
				type: 'error'
			})
			reject()
		} else {
			resolve()
		}
	})
}

const update = async item => {
	try {
		await updateBefore(item)

		dialog.value.state = 'update'
		dialog.value.title = '编辑角色'
		formState_reset(item)

		formData.value.map(v => {
			if (v.dataIndex === 'orgId') {
				v.disabled = true
			} else {
				v.disabled = false
			}
		})

		formState.value.platformId = item.platforms[0].id

		// const p = formData.value.find(v => {
		// 	return v.dataIndex === 'platformId'
		// })

		// const first = p.data.findIndex(v => {
		// 	const i = v.children.findIndex(u => {
		// 		if (u.value == item.platforms[0].id) {
		// 			return true
		// 		}
		// 	})
		// 	if (i > -1) {
		// 		return true
		// 	}
		// })

		// formState.value.platformId = [p.data[first].value, item.platforms[0].id]

		platformChange(formState.value.platformId, 'first')

		dialog.value.visible = true
	} catch (e) {
		console.log(e)
	}
}

const del = item => {
	ElMessageBox.confirm(`确定要删除[${item.name}]吗?此操作执行后不可恢复，请谨慎操作!`, '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			service.post('/sys/role/delete', [item.id]).then(res => {
				if (res.code === 0) {
					ElMessage({
						message: '删除成功!',
						type: 'success'
					})
					getList()
				} else {
					ElMessage({
						message: res.message,
						type: 'error'
					})
				}
			})
		})
		.catch(() => {
			console.log('取消')
		})
}

const details = async item => {
	try {
		await updateBefore(item)

		dialog.value.state = 'details'
		dialog.value.title = '角色详情'
		formState_reset(item)

		formData.value.map(v => {
			v.disabled = true
		})

		formState.value.platformId = item.platforms[0].id

		// const p = formData.value.find(v => {
		// 	return v.dataIndex === 'platformId'
		// })

		// const first = p.data.findIndex(v => {
		// 	const i = v.children.findIndex(u => {
		// 		if (u.value == item.platforms[0].id) {
		// 			return true
		// 		}
		// 	})
		// 	if (i > -1) {
		// 		return true
		// 	}
		// })

		// formState.value.platformId = [p.data[first].value, item.platforms[0].id]

		platformChange(formState.value.platformId, 'first')

		dialog.value.visible = true
	} catch (e) {
		console.log(e)
	}
}

const dialogSave = async () => {
	try {
		await modalForm.value.submit()
		dialog.value.loading = true
		const params = { ...formState.value, platformIdList: [formState.value.platformId] }
		delete params['platformId']
		if (dialog.value.state === 'add') {
			service
				.post('/sys/role/save', params)
				.then(res => {
					dialog.value.loading = false
					if (res.code === 0) {
						ElMessage({
							message: '新增成功!',
							type: 'success'
						})
						dialog.value.visible = false
						getList()
					} else {
						ElMessage({
							message: res.message,
							type: 'error'
						})
					}
				})
				.catch(e => {
					dialog.value.loading = false
				})
		} else {
			service
				.post('/sys/role/update', params)
				.then(res => {
					dialog.value.loading = false
					if (res.code === 0) {
						ElMessage({
							message: '修改成功!',
							type: 'success'
						})
						dialog.value.visible = false
						getList()
					} else {
						ElMessage({
							message: res.message,
							type: 'error'
						})
					}
				})
				.catch(e => {
					dialog.value.loading = false
				})
		}
	} catch (e) {
		console.log(e)
	}
}

// const state: IHooksOptions = reactive({
// 	dataListUrl: '/sys/role/page',
// 	deleteUrl: '/sys/role',
// 	queryForm: {
// 		name: ''
// 	}
// })

// const addOrUpdateRef = ref()
// const addOrUpdateHandle = (id?: number) => {
// 	addOrUpdateRef.value.init(id)
// }

// const dataScopeRef = ref()
const userVisible = ref(false)
const roleId = ref()
const userTitle = ref()
const handleCommand = row => {
	roleId.value = row.id
	userTitle.value = '关联用户 - ' + row.name
	userVisible.value = true
}

// const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle } = useCrud(state)
</script>

<style scoped>
.el-dropdown-link {
	display: flex;
	align-items: center;
	line-height: normal;
	margin-left: 10px;
}
</style>
